﻿using System;
using System.Collections.Generic;
using System.Deployment.Application;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CloudStorageLight.WpfClient
{
    /// <summary>
    /// LoginWindow.xaml の相互作用ロジック
    /// </summary>
    [ExcludeFromCodeCoverage]
    public partial class LoginWindow : Window
    {

        public MainVM Main { get; set; }

        public LoginWindow()
        {
            InitializeComponent();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            InstallUpdateSyncWithInfo();

            var settings = BlobDataManager.Instance.LoadSettings();
            this.BusyImage.Visibility = System.Windows.Visibility.Hidden;
            this.Service.Text = settings.LoginServiceUrl;
            this.EMail.Text = settings.LoginEmail;

            var user = BlobDataManager.Instance.LoadCachedUser(GetServiceUrl(this.Service.Text), this.EMail.Text);
            if (user != null && user.RememberMe)
            {
                this.Password.Password = BlobDataManager.DecryptedPassword(user.EncryptedPassword);
                this.RememberMe.IsChecked = true;
            }
        }

        private void LoginCommand_Click(object sender, RoutedEventArgs e)
        {
            var uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
            this.IsEnabled = false;
            this.Cursor = Cursors.Wait;
            this.BusyImage.Visibility = System.Windows.Visibility.Visible;
            var serviceUrl = this.Service.Text.Trim('/') + "/";
            string startPath = "/";
            if (serviceUrl.IndexOf("/f/") > 0)
            {
                startPath = serviceUrl.Substring(serviceUrl.IndexOf("/f/") + 2);
                serviceUrl = GetServiceUrl(serviceUrl);
            }
            BlobDataManager.Instance.LoginAsync(serviceUrl, this.EMail.Text, this.Password.Password, this.AdminRole.IsChecked == true, this.RememberMe.IsChecked == true).ContinueWith((x) =>
            {

                uiFactory.StartNew(() =>
                    {
                        var settings = BlobDataManager.Instance.LoadSettings();
                        settings.LoginServiceUrl = this.Service.Text;
                        settings.LoginEmail = this.EMail.Text;
                        BlobDataManager.Instance.SaveSettings(settings);

                        this.IsEnabled = true;
                        this.Cursor = Cursors.Arrow;
                        this.BusyImage.Visibility = System.Windows.Visibility.Hidden;

                        if (!x.IsFaulted && x.Result)
                        {
                            try
                            {
                                BlobDataManager.Instance.RestoreCachedFile(true);
                            }
                            catch (Exception ex)
                            {
                                Trace.WriteLine(ex.ToString());
                                MessageBox.Show(ex.Message);
                            }

                            string version = ApplicationDeployment.IsNetworkDeployed
                                    ? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()
                                    : Assembly.GetExecutingAssembly().GetName().Version.ToString();

                            if (Main == null)
                            {
                                var win = new MainWindow();
                                win.ViewModel.StartPath = startPath;
                                win.ViewModel.Title = "Cloud Storage Light " + version + " (" + BlobDataManager.Instance.LoginUser + ")";
                                win.Show();
                            }
                            else
                            {
                                Main.StartPath = startPath;
                                Main.Title = "Cloud Storage Light " + version + " (" + BlobDataManager.Instance.LoginUser + ")";
                                Main.Init();
                            }

                            if (serviceUrl.IndexOf("/f/") > 0)
                            {
                                serviceUrl = serviceUrl.Substring(0, serviceUrl.IndexOf("/f/")) + "/";

                            }

                            this.Close();

                        }
                        else
                        {
                            MessageBox.Show(Properties.Resources.MsgLoginFail);
                        }
                    });
            });
        }

        private static string GetServiceUrl(string serviceUrl)
        {
            if (serviceUrl.IndexOf("/f/") > 0)
            {
                serviceUrl = serviceUrl.Substring(0, serviceUrl.IndexOf("/f/")) + "/";
            }
            return serviceUrl.Trim('/') + "/";
        }

        private void CloseCommand_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void InstallUpdateSyncWithInfo()
        {
            UpdateCheckInfo info = null;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;

                try
                {
                    info = ad.CheckForDetailedUpdate();

                }
                catch (DeploymentDownloadException dde)
                {
                    MessageBox.Show(Properties.Resources.MsgInstallDeployError + dde.Message);
                    return;
                }
                catch (InvalidDeploymentException ide)
                {
                    MessageBox.Show(Properties.Resources.MsgInstallDeployError + ide.Message);
                    return;
                }
                catch (InvalidOperationException ioe)
                {
                    MessageBox.Show(Properties.Resources.MsgInstallInvalidError + ioe.Message);
                    return;
                }

                if (info.UpdateAvailable)
                {
                    Boolean doUpdate = true;

                    if (!info.IsUpdateRequired)
                    {
                        MessageBoxResult dr = MessageBox.Show(Properties.Resources.MsgInstallConfirm, "Update Available",
                            MessageBoxButton.OKCancel);
                        if (!(MessageBoxResult.OK == dr))
                        {
                            doUpdate = false;
                        }
                    }
                    else
                    {
                        // Display a message that the app MUST reboot. Display the minimum required version.
                        MessageBox.Show(
                            string.Format(Properties.Resources.MsgInstallMiniError, info.MinimumRequiredVersion.ToString()),
                            "Update Available", MessageBoxButton.OK, MessageBoxImage.Information);
                    }

                    if (doUpdate)
                    {
                        try
                        {
                            ad.Update();
                            MessageBox.Show(Properties.Resources.MsgInstallUpdated);
                            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
                            Application.Current.Shutdown();
                        }
                        catch (DeploymentDownloadException dde)
                        {
                            MessageBox.Show(Properties.Resources.MsgInstallCaNotInstall + dde);
                            return;
                        }
                    }
                }
            }
        }
    }
}
